package com.manage.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.beans.Photo;
import com.manage.util.QiNiuUtil;
import com.services.PhotoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by FCHEN on 2016/12/28.
 */
@Controller
@RequestMapping(value = "/qiniu")
public class QiniuController extends BaseController {
    @Autowired
    private PhotoService photoService;

    // @CrossOrigin
    @RequestMapping(value = "token")
    @ResponseBody
    public Map<String, String> getUploadToken() {
        Map<String, String> ret = new HashMap<>();
        ret.put("uptoken", QiNiuUtil.upToken());
        return ret;
    }

    @RequestMapping(value = "notify")
    @ResponseBody
    public String notifyUpdatePhotoUrl(@RequestBody Bean bean) {
        if (bean.code == 0) {
            String inputKey = bean.getInputKey();
            String sourceKey = bean.getItems().get(0).getKey();
            if (sourceKey != null && sourceKey.length() > 0) {
                //根据inputkey查询，更新图片链接
                Photo photo = new Photo();
                photo.setPhotoUrl(sourceKey);
                photo.setPhotoSource(inputKey);
                photoService.updateQUrl(photo);
            }
        }
        return "{}";
    }

    @RequestMapping(value = "query", produces = "application/json;charset=utf-8")
    @ResponseBody
    public String query(@RequestParam String q) {
        try {
            String url = "http://api.map.baidu.com/place/v2/suggestion?" +
                    "query=" + q +
                    "&region=青岛市" +
                    "&city_limit=true" +
                    "&output=json" +
                    "&ak=0Na7d5tLK7xKjZHFpT8RpWnCiMXp1b0N";
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            JSONObject jsonObject = JSONObject.parseObject(response.toString());
            JSONArray jsonArray = JSONArray.parseArray(jsonObject.get("result").toString());

            List strategyMap = new ArrayList();

            for (Object object : jsonArray) {
                JSONObject jo = JSONObject.parseObject(object.toString());
                JSONObject jo1 = JSONObject.parseObject(jo.get("location").toString());
                Map map = new HashMap();
                map.put("value", jo.get("name"));
                map.put("lat", jo1.get("lat"));
                map.put("lon", jo1.get("lng"));
                map.put("name", "百度收录地址");

                strategyMap.add(map);
            }

            return JSONArray.toJSONString(strategyMap);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "{\n" +
                "    \"status\":-1,\n" +
                "    \"message\":\"fail\"}";
    }

    public static class Query {
        String q;
    }

    public static class Bean {

        /**
         * id : z0.5aa0ff1bb9465319006e69fd
         * pipeline : 1381348441
         * code : 0
         * desc : The fop was completed successfully
         * reqid : cGsAAPaYWt0n5xkV
         * inputBucket :
         * inputKey : -LiaRW2Emej8S8MK-o4hnIo-RJ4=/Fga8FjmI_okCpHaAnRbRrM2yWudD
         * items : [{"cmd":"avthumb/mp4/ab/128k/ar/44100/acodec/libfaac|saveas/YnMtc2l0OmRmZGRkZA==","code":0,"desc":"The fop was completed successfully","hash":"FjA68hyOgxZgsPGzR6fuLTHqtYPv","key":"dfdddd","returnOld":0}]
         */

        private String id;
        private String pipeline;
        private int code;
        private String desc;
        private String reqid;
        private String inputBucket;
        private String inputKey;
        private List<ItemsBean> items;

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getPipeline() {
            return pipeline;
        }

        public void setPipeline(String pipeline) {
            this.pipeline = pipeline;
        }

        public int getCode() {
            return code;
        }

        public void setCode(int code) {
            this.code = code;
        }

        public String getDesc() {
            return desc;
        }

        public void setDesc(String desc) {
            this.desc = desc;
        }

        public String getReqid() {
            return reqid;
        }

        public void setReqid(String reqid) {
            this.reqid = reqid;
        }

        public String getInputBucket() {
            return inputBucket;
        }

        public void setInputBucket(String inputBucket) {
            this.inputBucket = inputBucket;
        }

        public String getInputKey() {
            return inputKey;
        }

        public void setInputKey(String inputKey) {
            this.inputKey = inputKey;
        }

        public List<ItemsBean> getItems() {
            return items;
        }

        public void setItems(List<ItemsBean> items) {
            this.items = items;
        }

        public static class ItemsBean {
            /**
             * cmd : avthumb/mp4/ab/128k/ar/44100/acodec/libfaac|saveas/YnMtc2l0OmRmZGRkZA==
             * code : 0
             * desc : The fop was completed successfully
             * hash : FjA68hyOgxZgsPGzR6fuLTHqtYPv
             * key : dfdddd
             * returnOld : 0
             */

            private String cmd;
            private int code;
            private String desc;
            private String hash;
            private String key;
            private int returnOld;

            public String getCmd() {
                return cmd;
            }

            public void setCmd(String cmd) {
                this.cmd = cmd;
            }

            public int getCode() {
                return code;
            }

            public void setCode(int code) {
                this.code = code;
            }

            public String getDesc() {
                return desc;
            }

            public void setDesc(String desc) {
                this.desc = desc;
            }

            public String getHash() {
                return hash;
            }

            public void setHash(String hash) {
                this.hash = hash;
            }

            public String getKey() {
                return key;
            }

            public void setKey(String key) {
                this.key = key;
            }

            public int getReturnOld() {
                return returnOld;
            }

            public void setReturnOld(int returnOld) {
                this.returnOld = returnOld;
            }
        }
    }
}
